﻿Imports Paypal_Manager.Service
Imports Paypal_Manager.Service.Paypal
Imports System.Threading

Public Class frmLogin
    Private Sub frmLogin_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        If My.Settings.User = "Username" Then
            SetupCueControl(TextBox1, "Username")
            SetupCueControl(TextBox2, "Password")
        Else
            TextBox1.Text = My.Settings.User
            TextBox2.Text = My.Settings.Pass
            CheckBox1.Checked = True
        End If
    End Sub
    Private Sub SetupCueControl(ByVal ctl As Control, ByVal sCue As String)
        With ctl
            .ForeColor = SystemColors.ControlDark
            .Text = sCue
        End With
    End Sub

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        PictureBox2.Visible = True
        If Not String.IsNullOrWhiteSpace(TextBox1.Text) AndAlso Not String.IsNullOrWhiteSpace(TextBox2.Text) Then
            If Not IsNothing(frmMain.PP) Then
                RemoveHandler frmMain.PP.Notify, AddressOf OnNotify
                frmMain.PP.Dispose()
            End If
            frmMain.PP = New Paypal(New String() {TextBox1.Text, TextBox2.Text})
            With frmMain.PP
                If CheckBox1.Checked Then
                    My.Settings.User = TextBox1.Text
                    My.Settings.Pass = TextBox2.Text
                    My.Settings.Save()
                Else
                    My.Settings.User = "Username"
                    My.Settings.Pass = "Password"
                    My.Settings.Save()
                End If
                AddHandler frmMain.PP.Notify, AddressOf OnNotify
                ThreadPool.QueueUserWorkItem(New WaitCallback(AddressOf .Login))
            End With
        End If
    End Sub
    Private Delegate Sub NotificationDelegate(ByVal Text As String)
    Private Sub OnNotify(ByVal Text As String)
        If Me.InvokeRequired Then
            Me.Invoke(New NotificationDelegate(AddressOf OnNotify), Text)
        Else
            If Text.Contains("Logged in") Then
                Debug.Print(String.Format("[{0}] {1}", Now.ToString("hh:mm:ss tt"), Text))
                PictureBox2.Visible = False
                frmMain.Show()
                Me.Close()
            ElseIf Text.Contains("Could not") Then
                Debug.Print(String.Format("[{0}] {1}", Now.ToString("hh:mm:ss tt"), Text))
                PictureBox2.Visible = False
                MessageBox.Show(Text)
            End If
        End If
    End Sub
End Class